import { defineStore } from 'pinia'

export const useCalculatorStore = defineStore('calculator', {
    state: () => ({
        num1: 0,
        num2: 0,
        operation: '+',
        result: null
    }),
    // 开启持久化配置
    persist: {
        // 存储到 localStorage（默认就是 localStorage，可省略）
        storage: localStorage,
        // 指定需要持久化的状态（不指定则默认持久化所有状态）
        paths: ['num1', 'num2', 'operation', 'result']
    },
    actions: {
        // 原有计算、更新、重置方法不变...
        calculate() {
            const n1 = Number(this.num1) || 0
            const n2 = Number(this.num2) || 0
            switch (this.operation) {
                case '+':
                    this.result = n1 + n2
                    break
                case '-':
                    this.result = n1 - n2
                    break
                case '*':
                    this.result = n1 * n2
                    break
                case '/':
                    this.result = n2 === 0 ? '除数不能为0' : n1 / n2
                    break
                default:
                    this.result = '请选择操作符'
            }
        },
        setNum1(value) {
            this.num1 = value
        },
        setNum2(value) {
            this.num2 = value
        },
        setOperation(op) {
            this.operation = op
        },
        reset() {
            this.num1 = 0
            this.num2 = 0
            this.operation = '+'
            this.result = null
        }
    }
})